package com.runfast.common.service.impl;

import com.runfast.common.dao.mapper.RunfastAgentbusinessMapper;
import com.runfast.common.dao.model.RunfastAgentbusiness;
import com.runfast.common.dao.model.RunfastAgentbusinessExample;
import com.runfast.common.service.BaseService;
import com.runfast.common.service.RunfastAgentbusinessService;
import com.runfast.common.utils.GeoUtil;
import com.runfast.paotui.entity.Region;
import com.runfast.paotui.utils.AmapUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.awt.geom.Point2D;
import java.util.ArrayList;
import java.util.List;

@Service
public class RunfastAgentbusinessServiceImpl extends BaseService<RunfastAgentbusiness, Integer, RunfastAgentbusinessExample> implements RunfastAgentbusinessService {

    @Resource
    private RedisTemplate redisTemplate;


    @Override
    public RunfastAgentbusinessMapper getMapper() {
        return (RunfastAgentbusinessMapper) super.getMapper();
    }

    /*@Override
    public RunfastAgentbusiness getAgentNearBy(Double lng, Double lat) {
        String namespace = "agent:";
        String regionKey = namespace + "region";

        HashOperations hashOperations = redisTemplate.opsForHash();



        List<Region> regions = AmapUtil.getRegins(lng + "," + lat, false);
        if(regions.isEmpty())return  null;//经纬度错误，高德地图都不知道你在哪里，附近的代理商就无从知晓
        Region userRegion = regions.get(0);
        String userTownship = userRegion.getTownship();
        String userDistrict = userRegion.getDistrict();
        String userCity = userRegion.getCity();
        String userProvince = userRegion.getProvince();


        List<RunfastAgentbusiness> agentList = getMapper().findAllAgent();

        List<RunfastAgentbusiness> branchAgentList = new ArrayList<>();
        List<RunfastAgentbusiness> leafAgentList = new ArrayList<>();
        for (RunfastAgentbusiness agent : agentList) {

            List<RunfastAgentbusiness> children = agent.getChildren();
            if(children!=null&&children.size()>0){
                branchAgentList.add(agent);
            }else{ //没有子代理商，直接经营者
                leafAgentList.add(agent);
            }
        }

        RunfastAgentbusiness agentFound = null;
        *//**
     * 优先考虑叶子代理商
     *//*
        agentFound =  getAgent(regionKey, hashOperations, userTownship, userDistrict, userCity, userProvince, leafAgentList);

        if(agentFound!=null) return agentFound;
        */

    /**
     * 考虑分支代理商
     *//*
        return getAgent(regionKey, hashOperations, userTownship, userDistrict, userCity, userProvince, branchAgentList);


    }*/
    private RunfastAgentbusiness getAgent(String regionKey, HashOperations hashOperations, String userTownship, String userDistrict, String userCity, String userProvince, List<RunfastAgentbusiness> agentList) {
        ArrayList<Region> candidateProvinces = new ArrayList<>();
        ArrayList<Region> candidateCities = new ArrayList<>();
        ArrayList<Region> candidateDistricts = new ArrayList<>();
        ArrayList<Region> candidateTownships = new ArrayList<>();
        for (RunfastAgentbusiness agent : agentList) { //考虑分支代理商

            Region agentRegion = (Region) hashOperations.get(regionKey, agent.getId());

            if (agentRegion == null) {
                RunfastAgentbusiness agentbusiness = agent;

                String province = agentbusiness.getProvince() == null ? "" : agentbusiness.getProvince();
                String city = agentbusiness.getCityName() == null ? "" : agentbusiness.getCityName();
                String district = agentbusiness.getCountyName() == null ? "" : agentbusiness.getCountyName();
                String township = agentbusiness.getArea() == null ? "" : agentbusiness.getArea();

                String address = province + city + district + township;
                List<String> locaions = AmapUtil.getLocaions(address, false);
                if (locaions.isEmpty()) continue;
                String location = locaions.get(0);

                List<Region> regins = AmapUtil.getRegins(location, false);
                Region region = regins.get(0);
                region.setAgentId(agentbusiness.getId());

                agentRegion = region;
                hashOperations.put(regionKey, agentbusiness.getId(), region);
            }

            String agentProvince = agentRegion.getProvince();

            if (StringUtils.isNotBlank(agentProvince) && agentProvince.equals(userProvince)) {
                candidateProvinces.add(agentRegion);
            }


        }

        for (Region region : candidateProvinces) {
            String city = region.getCity();

            if (StringUtils.isNotBlank(city) && city.equals(userCity)) {
                candidateCities.add(region);
            }
        }

        for (Region region : candidateCities) {

            String district = region.getDistrict();

            if (StringUtils.isNotBlank(district) && district.equals(userDistrict)) {
                candidateDistricts.add(region);
            }
        }

        for (Region region : candidateDistricts) {

            String township = region.getTownship();

            if (StringUtils.isNotBlank(township) && township.equals(userTownship)) {
                candidateTownships.add(region);
            }
        }

        if (candidateTownships.isEmpty()) {

            if (candidateDistricts.isEmpty()) {
                if (candidateCities.isEmpty()) {

                    if (candidateProvinces.isEmpty()) {
                        return null;
                    } else {

                        return getAgentbusiness(candidateProvinces);
                    }
                } else {
                    return getAgentbusiness(candidateCities);
                }

            } else {
                return getAgentbusiness(candidateDistricts);
            }
        } else {

            return getAgentbusiness(candidateTownships);
        }

    }


    private RunfastAgentbusiness getAgentbusiness(ArrayList<Region> candidateRegions) {
        Region region = candidateRegions.get(0);
        Integer agentId = region.getAgentId();
        return this.selectByPrimaryKey(agentId);
    }


    /**
     * 根据代理商
     *
     * @param lng
     * @param lat
     * @return
     */
    @Override
    public RunfastAgentbusiness getAgentNearByRange(Double lng, Double lat) {
        List<RunfastAgentbusiness> agentList = getMapper().findAllAgent();

        List<RunfastAgentbusiness> leafAgentList = new ArrayList<>();
        for (RunfastAgentbusiness agent : agentList) {

            List<RunfastAgentbusiness> children = agent.getChildren();
            //没有子代理商，直接经营者
            if (children.isEmpty()) leafAgentList.add(agent);
            else leafAgentList.addAll(children);
        }

        Point2D.Double piont = new Point2D.Double(lat, lng);
        for (RunfastAgentbusiness agentbusiness : leafAgentList) {
            String distRange = agentbusiness.getDistRange();

            if (StringUtils.isNotBlank(distRange)) {


                List<Point2D.Double> psList = new ArrayList<Point2D.Double>();
                String ps[] = distRange.split("\\|");

                for (String p : ps) {
                    if (StringUtils.isNotBlank(p)) {
                        String xs[] = p.split(",");
                        if (xs.length > 1) {
                            Point2D.Double p2d = new Point2D.Double(Double.parseDouble(xs[1]), Double.parseDouble(xs[0]));
                            psList.add(p2d);
                        }
                    }

                }

                if (GeoUtil.IsPtInPoly(piont, psList)) return agentbusiness;
            }

        }

        return null;


    }
}